package com.dycong.common.IO.socket.SSL.ssl;

import javax.net.ssl.*;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Properties;

/**
 * Created by dycong on 2017/3/28.
 */
public class ServerAuth {

    public static SSLContext getSSLContext() throws Exception {

        Properties properties = Configuration.getConfig();
        //todo keyManagers key 授权的密钥管理器，用来授权验证，验证客户端身份
        String serverCer = properties.getProperty("serverCer");
        char[] serverCerPwd = properties.getProperty("serverCerPwd").toCharArray();
        char[] serverKeyPwd = properties.getProperty("serverKeyPwd").toCharArray();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(serverCer), serverCerPwd);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(keyStore, serverKeyPwd);
        KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

        //todo TrustKeyStore 身份认证，第二个是被授权的证书管理器，向客户端证明自己的身份
        String serverTrustCer = properties.getProperty("serverTrustCer");
        char[] serverTrustCerPwd = properties.getProperty("serverTrustCerPwd").toCharArray();
        KeyStore trustKeyStore = KeyStore.getInstance("JKS");
        trustKeyStore.load(new FileInputStream(serverTrustCer), serverTrustCerPwd);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        trustManagerFactory.init(keyStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(keyManagers, trustManagers, null);
        return sslContext;
    }
}
